<script setup>

import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { Toast } from "vant";
import RecordsInfoApi from '../api/safetyCheck'
import { parseTime, base64ToFile, debounce } from "../../../utils";
import { VueSignaturePad } from 'vue-signature-pad';
import store from "@/store";
import {
  getToken,
} from "../../../utils/auth";
import _ from "lodash";
import axios from "axios";
onMounted(() => {
  loading.value = true
  // queryByCond()
})
const vanFormRef = ref(null)
const shiftType = Array.from(store.getters.dictMap).filter(entry => entry.groupCode === "shift_type");
const currentStage = Array.from(store.getters.dictMap).filter(entry => entry.groupCode === "current_stage");
const signaturePad = ref(null)
const showWrite = ref(false)
const signatureShow = ref(false)
const activeName = ref(['1'])
const router = useRouter();
const onClickLeft = () => router.push('/main');
const onClickRight = () => router.push('/recordsInfo/add');
const writeStatus = ref(1)
const shiftStatus = ref(1)
const safetyCheckId = ref(null)
const loading = ref(false)
const currentDate = ref(new Date());
//new Date().getFullYear,(new Date().getMonth() + 1).toString().padStart(2, '0')
const columnsType = ['year', 'month'];
const timeShow=ref(false)
const searchValue=ref(parseTime(new Date(), '{y}-{m}'))
const minDate=new Date(2025, 1, 1)
// 列表数据
const dataSorce = ref({
  list: []
})
const formState = ref({
  inPerson: '',
  notes: ''
})

// 获取列表数据
const finished = ref(false);
const pageSize = ref(10)
const pageNum = ref(1)

const queryByCond = () => {
  return new Promise((resolve, reject) => {
    RecordsInfoApi.queryByCond({ id: store.getters.deptId == 0 ? undefined : store.getters.deptId,month:searchValue.value }, pageSize.value, pageNum.value)
      .then((response) => {
        loading.value = false
        const data = response.data
        if (data.code === 200) {
          dataSorce.value.list = dataSorce.value.list.concat(data.data.list);
          if (data.data.isLastPage) {
            finished.value = data.data.isLastPage;
            return;
          }
          pageNum.value += 1;
        } else {
          Toast.fail(data.message);
          reject();
        }
      })
      .catch((error) => {
        loading.value = false
        if (error.message !== "") {
          Toast.fail(error.message);
        }
        reject(error);
      });
  });
}
const options = ref({
  penColor: '#000000',
  minWidth: 2,
  maxWidth: 2,
  backgroundColor: "rgba(255, 255, 255)",
});


// 跳转详情
const goDetail = (checkId) => {

  router.push({
    path: '/recordsInfo/detail',
    query: {
      id: checkId
    }
  })
}
const goAdd = (checkId, status) => {

  router.push({
    path: '/safetyCheck_bqqiwj3z/add',
    query: {
      id: checkId,
      type: status
    }
  })
}
const clearSign = () => {
  signaturePad.value.clearSignature();
};
const saveUploadSign = async () => {

  const { isEmpty, data } = signaturePad.value.saveSignature();
  if (isEmpty) return;
  showWrite.value = false
  signaturePad.value.clearSignature();
  let writeUrl = await changImg(data)
  let writeId = await uploadFile([base64ToFile(writeUrl, "qianming.png")])
  let params = {
    checkId: safetyCheckId.value,
    currentStage: 2,
  }
  RecordsInfoApi.update(params).then(async res => {
    await RecordsInfoApi.updateTingSignature({ checkId: safetyCheckId.value, baoSignature: writeId[0].id, ...formState.value })
    // if (writeStatus.value == 1) {
    //   if (shiftStatus.value == 1) {
    //     await RecordsInfoApi.updateBaoSignature({ checkId: safetyCheckId.value, baoSignature: writeId[0].id })
    //   } else if (shiftStatus.value == 2) {
    //     RecordsInfoApi.updateBaoSignatureMid({ checkId: safetyCheckId.value, baoSignature: writeId[0].id })
    //   } else if (shiftStatus.value == 3) {
    //     RecordsInfoApi.updateBaoSignaturePost({ checkId: safetyCheckId.value, baoSignature: writeId[0].id })
    //   }
    // } else {
    //   await RecordsInfoApi.updateTingSignature({ checkId: safetyCheckId.value, baoSignature: writeId[0].id })
    // }

    Toast.success("签名成功")
    pageNum.value = 1
    queryByCond()
    dataSorce.value.list = []
    formState.value = {
      inPerson: '',
      notes: ''
    }
  })

}
const baoAnWrite = (id, currentStage, shift) => {
  signatureShow.value = true

  safetyCheckId.value = id
  writeStatus.value = currentStage
  shiftStatus.value = shift
}
const closeSign = () => {
  signaturePad.value.clearSignature();
  showWrite.value = false
}
async function uploadFile(files) {
  return new Promise(async (resolve, reject) => {
    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
      formData.append('files', files[i]); // 添加每个文件到 FormData 中
    }

    try {
      const response = await axios.post(import.meta.env.VITE_APP_BASE_API + '/sysfiles/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          "Authorization": getToken()
        }
      });

      resolve(response.data.data)
    } catch (error) {
      console.error('文件上传失败:', error);
    }
  })

}
const changImg = (base64Image) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = base64Image;
    img.onload = function () {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');

      // 旋转 90 度，交换宽高
      canvas.width = img.height;
      canvas.height = img.width;

      // 移动原点到左下角
      ctx.translate(0, canvas.height);
      // 逆时针旋转 90 度，使用负角度
      ctx.rotate(-Math.PI / 2);

      // 绘制图片
      ctx.drawImage(img, 0, 0);

      // 获取旋转后的 Base64 数据
      const rotatedBase64 = canvas.toDataURL('image/png');
      resolve(rotatedBase64)
    }
  })

}
function isToday(date) {
  if (!date) return false;

  try {
    const inputDate = new Date(date);
    if (isNaN(inputDate.getTime())) return false;

    const today = new Date();
    const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    const todayEnd = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);

    return inputDate >= todayStart && inputDate < todayEnd;
  } catch (e) {
    return false;
  }
}
const handleCancel = () => {
  formState.value = {
    inPerson: '',
    notes: ''
  }
  signatureShow.value = false
}
const onSubmit = debounce(() => {

  signatureShow.value = false
  showWrite.value = true

}, 1000)

const onFailed = (errorInfo) => {
  Toast.fail('提交失败,完善信息')
  console.log('failed', errorInfo);
}
const onLoad = _.debounce(() => {
  queryByCond();
}, 1000);
const onConfirm=(value)=>{
  timeShow.value=false
  searchValue.value=parseTime(currentDate.value, '{y}-{m}')
  dataSorce.value.list = []
  pageNum.value=1
  queryByCond()
  
}
</script>

<template>
  <div class="list-page">
    <van-nav-bar title="审核记录" left-text="返回" left-arrow @click-left="onClickLeft" @click-right="onClickRight">

    </van-nav-bar>
    <van-cell class="search" title="选择时间" is-link :value="searchValue" @click="timeShow=true" />
    <van-list class="list" :finished="finished" finished-text="没有更多了" @load="onLoad">
      <van-loading v-if="loading" size="24px" color="#1890ff" vertical>加载中...</van-loading>
      <div v-else>
        <van-cell class="list-item" v-for="item in dataSorce.list" :key="item.id" @click.stop="goDetail(item.checkId)">
          <template #default>
            <div class="blue-bar"></div>
            <div style="padding:0 18px 18px 18px;display: flex;flex-direction: column;gap: 10px;">
              <div><span class="groupTitle">营业厅：</span>{{ item.yytname }}</div>
              <div><span class="groupTitle">时间：</span>{{ item.checkDate }}</div>
              <div><span class="groupTitle">当前状态：</span>{{ item.shiftType ? shiftType[item.shiftType - 1].label : '' }}
              </div>
              <div><span class="groupTitle">创建人：</span>{{ item.createdName }}</div>
              <div><span class="groupTitle">当前流程：</span>
                <van-tag plain type="primary" v-if="item.currentStage == 1" size="large">{{ item.currentStage ?
                  currentStage[item.currentStage - 1].label : '' }}
                </van-tag>
                <van-tag plain type="success" v-if="item.currentStage == 2" size="large">{{ item.currentStage ?
                  currentStage[item.currentStage - 1].label : '' }}
                </van-tag>
                <!-- <van-tag plain type="success" v-if="item.currentStage == 3 "
                  size="large">{{ item.currentStage ? currentStage[item.currentStage - 1].label : '' }}
                </van-tag> -->
              </div>
            </div>
            <van-steps :active="item.shiftType - 1" active-color="#1989fa">
              <van-step>班前检查</van-step>
              <van-step>班中检查</van-step>
              <van-step>班后检查</van-step>
            </van-steps>
            <div v-if="isToday(item.checkDate)" style="position: absolute; top:0px;right:0px"><van-tag size="large"
                round type="primary">当日提交</van-tag></div>
            <div style="display: flex; justify-content: center; gap: 20px;">
              <!-- <van-button type="primary" size="small"
                @click.stop="baoAnWrite(item.checkId, item.currentStage, item.shiftType)"
                v-if="item.currentStage == 1 &&  store.getters.roles.indexOf('bao_an') != -1">值班保安确认签字</van-button> -->
              <!-- <van-button type="primary" size="small" style="font-weight: bold;font-size: 14px;letter-spacing: 2px;"
                @click.stop="baoAnWrite(item.checkId, item.currentStage, item.shiftType)"
                v-if="item.currentStage == 1 && item.shiftType == 3 && store.getters.roles.indexOf('ting_jing_li') != -1">厅经理确认签字</van-button>
              <van-button type="warning" size="small" style="font-weight: bold;font-size: 14px;letter-spacing: 2px;"
                @click.stop="goAdd(item.checkId, 1)"
                v-if="item.currentStage == 1 && item.shiftType == 1 && store.getters.roles.indexOf('an_quan_yuan') != -1">添加班中记录</van-button>
              <van-button type="success" size="small" style="font-weight: bold;font-size: 14px;letter-spacing: 2px;"
                @click.stop="goAdd(item.checkId, 2)"
                v-if="item.currentStage == 1 && item.shiftType == 2 && store.getters.roles.indexOf('an_quan_yuan') != -1">添加班后记录</van-button> -->
              <van-button type="primary" size="small" style="font-weight: bold;font-size: 14px;letter-spacing: 2px;"
                @click.stop="baoAnWrite(item.checkId, item.currentStage, item.shiftType)"
                v-if="item.currentStage == 1 && item.shiftType == 3 && store.getters.roles.indexOf('super_admin') == -1">厅经理确认签字</van-button>
              <van-button type="warning" size="small" style="font-weight: bold;font-size: 14px;letter-spacing: 2px;"
                @click.stop="goAdd(item.checkId, 1)"
                v-if="item.currentStage == 1 && item.shiftType == 1 && store.getters.roles.indexOf('super_admin') == -1">添加班中记录</van-button>
              <van-button type="success" size="small" style="font-weight: bold;font-size: 14px;letter-spacing: 2px;"
                @click.stop="goAdd(item.checkId, 2)"
                v-if="item.currentStage == 1 && item.shiftType == 2 && store.getters.roles.indexOf('super_admin') == -1">添加班后记录</van-button>

            </div>
          </template>
        </van-cell>
      </div>

    </van-list>
  </div>
  <van-popup v-model:show="showWrite">
    <div style="width: 90vw; height: 80vh;position: relative;overflow: hidden;">
      <VueSignaturePad ref="signaturePad" class="signature" :options="options" width="100%" height="100%">
      </VueSignaturePad>
      <div style="display: flex; transform: rotate(90deg); gap: 10px;bottom: 100px;left: -50px; position: absolute;">
        <van-button type="danger" @click="closeSign">关闭</van-button>
        <van-button type="warning" @click="clearSign">清屏</van-button>
        <van-button type="primary" @click="saveUploadSign">确认</van-button>
      </div>
    </div>
  </van-popup>
  <van-dialog v-model:show="signatureShow" title="签名确认" :show-cancel-button="false" :close-on-click-overlay="true"
    :show-confirm-button="false" :before-close="handleCancel">
    <div style="margin: 10px 0;">
      <van-form ref="vanFormRef" @submit="onSubmit" @failed="onFailed">
        <van-field class="groupField" required name="inPerson" label="是否本人签字：" label-width="110px"
          :rules="[{ required: true, message: '请选择是否' }]">
          <template #input>
            <van-radio-group v-model="formState.inPerson" direction="horizontal">
              <van-radio name="1">是</van-radio>
              <van-radio name="0">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field v-if="formState.inPerson == 0" v-model="formState.notes" required label="原因说明：" type="textarea"
          placeholder="请输入原因说明" rows="5" autosize :rules="[{ required: true, message: '请输入原因' }]" />
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </div>

  </van-dialog>
  <van-popup v-model:show="timeShow" position="bottom">
    <van-datetime-picker  type="year-month" v-model="currentDate" title="选择年月" :min-date="minDate" 
      :columns-type="columnsType"  @confirm="onConfirm"
      @cancel="timeShow=false" />
  </van-popup>
</template>

<style scoped>
:deep(.search .van-cell__title){
  text-align: left;
}
.list-page {
  background: #ebedf0;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;
}

.list {
  padding-bottom: 60px;
}

.list-item {
  margin: 16px 16px 0 16px;
  border-radius: 8px;
  width: auto;
}

.blue-bar {
  background: #1989fa;
  width: 2px;
  height: 16px;
  display: inline-block;
  position: absolute;
  top: 3px;
  border-radius: 5px;
}

.item-title {
  margin-left: 8px;
  font-size: 16px;
  font-weight: 800;
}

.groupTitle {
  width: 70%;
  font-weight: bold;
  color: #000;
}
</style>